package com.cookor.poi.modules.phy.mobile;

import com.cookor.poi.common.utils.DateUtils;
import com.cookor.poi.common.utils.IdGen;
import com.cookor.poi.common.utils.JedisUtils;
import com.cookor.poi.common.utils.ResultUtil;
import com.cookor.poi.common.utils.StringUtils;
import com.cookor.poi.modules.phy.dto.DateDto;
import com.cookor.poi.modules.phy.entity.FSchedue;
import com.cookor.poi.modules.phy.service.FSchedueService;
import com.cookor.poi.modules.tenant.entity.TTenant;
import com.cookor.poi.modules.tenant.service.TTenantService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/api/phy/appoint"})
@ResponseBody
public class ApiAppointController extends ApiBaseController {
    @Autowired
    private FSchedueService fSchedueService;

    @Autowired
    private TTenantService tTenantService;

    @RequestMapping({"/list"})
    public ResultUtil appointListString(String date, HttpServletRequest request) {
        ResultUtil result = getResult();
        try {
            List<FSchedue> list;
            Integer tenantId = getTenantId(request);
            Object isOpen = JedisUtils.get("isOpenA");
            if (isOpen == null) {
                if (Calendar.getInstance().get(11) >= 9) {
                    JedisUtils.set("isOpenA", "1", 3600);
                    list = getResA(date, tenantId);
                    if (StringUtils.isBlank(date)) {
                        JedisUtils.setObject("fschedueList", list, 60);
                    } else {
                        JedisUtils.setObject(date, list, 60);
                    }
                } else if (StringUtils.isBlank(date)) {
                    if (JedisUtils.getObject("fschedueList") == null) {
                        list = getResA(date, tenantId);
                        JedisUtils.setObject("fschedueList", list, 60);
                    } else {
                        list = (List<FSchedue>) JedisUtils.getObject("fschedueList");
                    }
                } else if (JedisUtils.getObject(date) == null) {
                    list = getResA(date, tenantId);
                    JedisUtils.setObject(date, list, 60);
                } else {
                    list = (List<FSchedue>) JedisUtils.getObject(date);
                }
            } else if (StringUtils.isBlank(date)) {
                if (JedisUtils.getObject("fschedueList") == null) {
                    list = getResA(date, tenantId);
                    JedisUtils.setObject("fschedueList", list, 60);
                } else {
                    list = (List<FSchedue>) JedisUtils.getObject("fschedueList");
                }
            } else if (JedisUtils.getObject(date) == null) {
                list = getResA(date, tenantId);
                JedisUtils.setObject(date, list, 60);
            } else {
                list = (List<FSchedue>) JedisUtils.getObject(date);
            }
            result.putParams("data", list.get(0));
            Object tenantObj = JedisUtils.getObject("tenant");
            if (tenantObj != null) {
                result.putParams("tenant", tenantObj);
            } else {
                TTenant tenant = this.tTenantService.get(tenantId.toString());
                JedisUtils.setObject("tenant", tenant, 1800);
                result.putParams("tenant", tenant);
            }
            String uuid = JedisUtils.get("uuid");
            if (uuid == null) {
                uuid = IdGen.uuid();
                JedisUtils.set("uuid", uuid, 7200);
            }
            result.putParams("uuid", uuid);
        } catch (Exception e) {
            result.setCode(ResultUtil.ERROR_CODE);
            result.setError(e.getMessage());
            this.logger.error("ApiAppointController appointList error!", e);
        }
        return result;
    }

    @RequestMapping({"/dateList"})
    public ResultUtil dateList(HttpServletRequest request) {

        ResultUtil result = getResult();
        try {
            List<DateDto> dateList;
            Object isOpen = JedisUtils.get("isOpenB");
            if (isOpen == null) {
                if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
                    JedisUtils.set("isOpenB", "1", 1800);
                    dateList = getResB(getTenantId(request));
                    JedisUtils.setObject("dateList", dateList, 60);
                } else if (JedisUtils.getObject("dateList") == null) {
                    dateList = getResB(getTenantId(request));
                    JedisUtils.setObject("dateList", dateList, 60);
                } else {
                    dateList = (List<DateDto>) JedisUtils.getObject("dateList");
                }
            } else if (JedisUtils.getObject("dateList") == null) {
                dateList = getResB(getTenantId(request));
                JedisUtils.setObject("dateList", dateList, 60);
            } else {
                dateList = (List<DateDto>) JedisUtils.getObject("dateList");
            }
            result.putParams("dateList", dateList);
        } catch (Exception e) {
            result.setCode(ResultUtil.ERROR_CODE);
            result.setError(e.getMessage());
            this.logger.error("ApiAppointController dateList error!", e);
        }
        return result;
    }

    private List<FSchedue> getResA(String date, Integer tenantId) throws Exception {
        Integer year = null;
        Integer month = null;
        Integer day = null;
        Calendar c = Calendar.getInstance();
        if (StringUtils.isBlank(date)) {
            FSchedue fSchedue = new FSchedue();
            fSchedue.setTenantId(tenantId);
            List<FSchedue> list1 = this.fSchedueService.findList(fSchedue);
            int i = 0;
            boolean flag = true;
            while (flag && i < 32) {
                DateDto futureDate = DateUtils.getFutureDate(i);
                for (FSchedue fSchedue1 : list1) {
                    year = futureDate.getYear();
                    String monthStr = futureDate.getDate().split("-")[0];
                    String dayStr = futureDate.getDate().split("-")[1];
                    month = Integer.valueOf(Integer.parseInt((monthStr.indexOf("0") == 0) ? monthStr.substring(1) : monthStr));
                    day = Integer.valueOf(Integer.parseInt((dayStr.indexOf("0") == 0) ? dayStr.substring(1) : dayStr));
                    if (fSchedue1.getScheduleYear().equals(year) && fSchedue1.getScheduleMonth().equals(month) && fSchedue1
                            .getScheduleDay().equals(day)) {
                        if ((fSchedue1.getTotalA() == null || fSchedue1.getTotalA().equals(Integer.valueOf(0))) && (fSchedue1
                                .getTotalB() == null || fSchedue1.getTotalB().equals(Integer.valueOf(0))) && (fSchedue1
                                .getTotalC() == null || fSchedue1.getTotalC().equals(Integer.valueOf(0))) && (fSchedue1
                                .getTotalD() == null || fSchedue1.getTotalD().equals(Integer.valueOf(0))) && (fSchedue1
                                .getTotalE() == null || fSchedue1.getTotalE().equals(Integer.valueOf(0))))
                            break;
                        flag = false;
                        break;
                    }
                }
                i++;
            }
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = sdf.parse(date);
            c.setTime(parse);
            year = Integer.valueOf(c.get(1));
            month = Integer.valueOf(c.get(2) + 1);
            day = Integer.valueOf(c.get(5));
        }
        FSchedue query = new FSchedue();
        query.setTenantId(tenantId);
        query.setScheduleYear(year);
        query.setScheduleMonth(month);
        query.setScheduleDay(day);
        List<FSchedue> list = this.fSchedueService.findList(query);
        return list;
    }

    private List<DateDto> getResB(Integer tenantId) {
        FSchedue query = new FSchedue();
        query.setTenantId(tenantId);
        List<FSchedue> list = this.fSchedueService.findList(query);
        List<DateDto> dateList = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        int hour = c.get(11);
        int i = 0;
        boolean flag = true;
        boolean breakFlag = false;
        int week = c.get(Calendar.DAY_OF_WEEK);
        //TODO
//        if(c != null){
//            return dateList;
//        }
        while (flag) {
            DateDto futureDate = DateUtils.getFutureDate(i);
            for (FSchedue fSchedue : list) {
                Integer year = futureDate.getYear();
                String monthStr = futureDate.getDate().split("-")[0];
                String dayStr = futureDate.getDate().split("-")[1];
                Integer month = Integer.valueOf(Integer.parseInt((monthStr.indexOf("0") == 0) ? monthStr.substring(1) : monthStr));
                Integer day = Integer.valueOf(Integer.parseInt((dayStr.indexOf("0") == 0) ? dayStr.substring(1) : dayStr));
                // 特殊假日的处理方式
//                if (day != 6 && day != 7) {
//                    continue;
//                }
//                if (fSchedue.getScheduleYear().equals(year) && fSchedue.getScheduleMonth().equals(month) && fSchedue
//                        .getScheduleDay().equals(day)) {
//                    dateList.add(futureDate);
//                    //flag = false;
//                    break;
//                }
//            }
//            if (hour > 7) {
//                if (dateList.size() > 1) {
//                    flag = false;
//                }
//            } else if (dateList.size() > 0) {
//                flag = false;
//            }
//            i++;
                // 平日的处理方式
                if (fSchedue.getScheduleYear().equals(year) && fSchedue.getScheduleMonth().equals(month) && fSchedue
                        .getScheduleDay().equals(day)) {
                    if ((fSchedue.getTotalA() == null || fSchedue.getTotalA().equals(Integer.valueOf(0))) && (fSchedue
                            .getTotalB() == null || fSchedue.getTotalB().equals(Integer.valueOf(0))) && (fSchedue
                            .getTotalC() == null || fSchedue.getTotalC().equals(Integer.valueOf(0))) && (fSchedue
                            .getTotalD() == null || fSchedue.getTotalD().equals(Integer.valueOf(0))) && (fSchedue
                            .getTotalE() == null || fSchedue.getTotalE().equals(Integer.valueOf(0)))) {
                        break;
                    }
                    if (dateList.size() == 0 && i != 0) {
                        breakFlag = true;
                    }
                    dateList.add(futureDate);
                    break;
                }
            }
            if (hour > 7) {
//                if ((dateList.size() == 1 && breakFlag) || dateList.size() > 1) {
//                    flag = false;
//                }
                if(breakFlag){ // 当日没有号源
                    if (dateList.size() > 0) { // 那就往后找一天
                        flag = false;
                    }
                }else{
                    if (dateList.size() > 1) { // 否则就往后找两天
                        flag = false;
                    }
                }
//                if (dateList.size() > 1) {
//                    flag = false;
//                }
            } else if (dateList.size() > 0) {
                flag = false;
            }
            i++;
//            if (week == 6 && i > 3) { //周五往后推三天
//                flag = false;
//            }
//            if (week == 7 && i > 2) { //周六往后推二天
//                flag = false;
//            }
//            if (week == 1 && i > 1) { //周日往后推一天
//                flag = false;
//            }
//            if ((week != 6 && week != 7 && week != 1) && i > 1) { // 平常就当日
//                flag = false;
//            }

        }
        return dateList;
    }
}
